﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SDATA;
using SDLL;
using DevComponents.DotNetBar.SuperGrid;
using SGUI;

namespace SABI
{
    public partial class MK0001 : Form
    {
        string sql = "", _DivisionList, _GroupList, _Notes;
        DataTable dt_Division = new DataTable();
        DataTable dt_Group = new DataTable();
        DataTable dt_Level = new DataTable();

        public MK0001()
        {
            InitializeComponent();
        }

        private void MK0001_Load(object sender, EventArgs e)
        {

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            (Application.OpenForms["frmHome"] as frmHOME).CloseTab(this);
        }

        private void MK0001_Shown(object sender, EventArgs e)
        {
            loadDATA_Combo();
            loadDATA_Grid2();
        }

        void loadDATA_Combo()
        {

            sql = "SELECT ID, GroupID, GroupName, DivisionList, GroupList, IsUpdateVoucherDate, IsLockUnitPrice FROM tb0070 ORDER BY GroupID";
            TDBCboGroupID.DataSource = FRM.GetDataTable(sql);
            
            Application.DoEvents();
            
        }

        void loadDATA_Grid1()
        {
            sql = string.Format("SELECT ID, DivisionID, DivisionName, CASE WHEN CHARINDEX(DivisionID,'{0}')>0 THEN 1 ELSE 0 END AS IsCheck FROM tb0038 ORDER BY DivisionID", _DivisionList);
            dt_Division = FRM.GetDataTable(sql);

            sql = string.Format("SELECT ID, GroupID, GroupName, CASE WHEN CHARINDEX(CAST(ID as varchar(20)),'{0}')>0 THEN 1 ELSE 0 END AS IsCheck FROM tb0070 ORDER BY GroupName", _GroupList);
            dt_Group = FRM.GetDataTable(sql);

            lstDivisionShow.Items.Clear();
            for (int i = 0; i < dt_Division.Rows.Count; i++)
                lstDivisionShow.Items.Add(string.Format("{0}. {1}", dt_Division.Rows[i]["DivisionID"], dt_Division.Rows[i]["DivisionName"]), dt_Division.Rows[i]["IsCheck"].ToString() == "1" ? CheckState.Checked : CheckState.Unchecked);

            lstGroupShow.Items.Clear();
            for (int i = 0; i < dt_Group.Rows.Count; i++)
                lstGroupShow.Items.Add(string.Format("{0}. {1}", dt_Group.Rows[i]["ID"], dt_Group.Rows[i]["GroupName"]), dt_Group.Rows[i]["IsCheck"].ToString() == "1" ? CheckState.Checked : CheckState.Unchecked);

            sql = "SELECT ID,Name,a.FormID, a.IconID, a.ModuleID, a.ParentID, a.Notes, ";
            sql += "b.IsView, b.IsNew, b.IsUpdate, b.IsPrint, b.IsDelete, b.IsExport ";
            sql += string.Format("FROM (SELECT * FROM MK0000 WHERE Disabled=0) a left join (SELECT * FROM MK0001 WHERE GroupID='{0}' ) b ON (a.ID=b.TaskID) order by a.ID,a.Notes", TDBCboGroupID.Text);
            dt_Level = FRM.GetDataTable(sql);
            GridDB1.PrimaryGrid.DataSource = dt_Level;
            Application.DoEvents();
            loadNode();
            chkOpenAllLevel_CheckedChanged(null, null);
        }

        void loadDATA_Grid2()
        {
            sql = "SELECT * FROM MK0000 ORDER BY ID, ParentID";
            DataTable dt = FRM.GetDataTable(sql);
            DBRender.GridDB(GridDB2, dt);

            sql = "SELECT ID IDs, Name Names, Notes FROM MK0000 ORDER BY ID, ParentID";
            TDBParentID.DataSource = FRM.GetDataTable(sql);

            sql = "SELECT ModuleID FROM MK0000 GROUP BY ModuleID";
            cbxModuleID.DataSource = FRM.GetDataTable(sql);
            cbxModuleID.ValueMember = "ModuleID";
            cbxModuleID.DisplayMember = "ModuleID";

        }

        void loadNode()
        {
            if (GridDB1.PrimaryGrid.Rows.Count < 1) { return; }
            for(int i=0; i<GridDB1.PrimaryGrid.Rows.Count;i++)
            {
                GridRow gr = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                int notes = int.Parse(gr.Cells["clNotes"].Value.ToString());
                if (gr.Cells["clFormID"].Value.ToString() == "")
                {
                    gr.Cells["clName"].Value = "[-] " + gr.Cells["clName"].Value.ToString();
                    if(gr.Cells["clNotes"].Value.ToString() == "0")
                        gr.CellStyles.Default.Background = new DevComponents.DotNetBar.SuperGrid.Style.Background(Color.LightSkyBlue);
                    else
                        gr.CellStyles.Default.Background = new DevComponents.DotNetBar.SuperGrid.Style.Background(Color.FromArgb(235,235,235));
                    gr.Cells["clOpen"].Value = true;
                }
                else
                {
                    gr.Cells["clName"].Value = "     " + gr.Cells["clName"].Value.ToString();
                    gr.Cells["clOpen"].Value = false;
                }
                if(notes>0)
                    gr.Cells["clName"].Value = "".PadLeft(notes * 6, ' ') + gr.Cells["clName"].Value.ToString();
            }
            //Hide all
            //for (int i = 0; i < dgvT.PrimaryGrid.Rows.Count; i++)
            //{
            //    GridRow gr2 = (GridRow)dgvT.PrimaryGrid.Rows[i];
            //    if (gr2.Cells["clParentID"].Value.ToString().Trim() == "0")
            //    {
            //        HideRow(gr2);
            //    }
            //}
        }

        private void dgvT_CellDoubleClick(object sender, GridCellDoubleClickEventArgs e)
        {
            GridRow gr = ((GridRow)GridDB1.PrimaryGrid.Rows[e.GridCell.RowIndex]);
            if (dt_Level.Select("ParentID='" + gr.Cells["clID"].Value.ToString().Trim() + "'").Count() < 1) { return; }
            bool isOpen = gr.Cells["clOpen"].Value == null ? false : !(bool)gr.Cells["clOpen"].Value;
            gr.Cells["clOpen"].Value = isOpen;
            SubRow(gr, isOpen);
            HideRow(gr,isOpen);
        }

        void HideRow(GridRow gr, bool open=false)
        {
            if (dt_Level.Select("ParentID='" + gr.Cells["clID"].Value.ToString().Trim() + "'").Count() < 1) { return; }
            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                GridRow gr2 = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                if(gr2.Cells["clParentID"].Value.ToString().Trim() == gr.Cells["clID"].Value.ToString().Trim())
                {
                    gr2.Visible = open;
                    if(!open)
                    {
                        gr2.Cells["clOpen"].Value = open;
                        SubRow(gr2, open);
                        HideRow(gr2, open);
                    }                    
                }
            }
        }

        void SubRow(GridRow gr, bool open=false)
        {
            if (open)
                gr.Cells["clName"].Value = gr.Cells["clName"].Value.ToString().Replace("[+]", "[-]");
            else
                gr.Cells["clName"].Value = gr.Cells["clName"].Value.ToString().Replace("[-]", "[+]");
                    
        }

        private void dgvT_CellClick(object sender, GridCellClickEventArgs e)
        {
            if (e.GridCell.ColumnIndex < 1 || e.GridCell.ColumnIndex > 6) { return; }
            GridRow gr = ((GridRow)GridDB1.PrimaryGrid.Rows[e.GridCell.RowIndex]);
            bool ischk = false;
            bool root = false;
            if(gr.Cells[e.GridCell.ColumnIndex].Value.ToString()!="")
            {
                ischk = gr.Cells[e.GridCell.ColumnIndex].Value.ToString() == "1" ? true : false;
                root = gr.Cells["clNotes"].Value.ToString() == "0" ? true : false;
                CheckRow(gr,e.GridCell.ColumnIndex,ischk,root);
            }           
            
        }

        void CheckRow(GridRow gr, int colindex, bool chk, bool root=false)
        {
            string _id = gr.Cells["clID"].Value.ToString();
            string _parent = gr.Cells["clParentID"].Value.ToString();
            if (gr.Cells["clFormID"].Value.ToString() == "" && colindex<9)
            {
                //check all children
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                {
                    GridRow gr2 = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                    if (gr2.Cells["clParentID"].Value.ToString() == _id)
                    {
                        GridDB1.GetCell(i, colindex).Value = chk;
                        if (gr2.Cells["clFormID"].Value.ToString() == "")
                            CheckRow(gr2, colindex, chk,root);
                    }
                }
                if (!root) { CheckRow(gr, colindex * 10, chk,root); } // || gr.Cells["clNotes"].Value.ToString() != "0"
            }
            else
            {
                if (colindex > 9) { colindex /= 10; }
                bool isdongbo = true;
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                {
                    GridRow gr2 = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                    if (gr2.Cells["clParentID"].Value.ToString() == _parent)
                    {
                        bool ischk = false;
                        if (gr2.Cells[colindex].Value.ToString() != "")
                            ischk = gr2.Cells[colindex].Value.ToString() == "1" ? true : false;
                        if (ischk != chk)
                        {
                            isdongbo = false;
                            break;
                        }
                    }
                }
                for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
                {
                    GridRow gr2 = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                    if (gr2.Cells["clID"].Value.ToString() == _parent)
                    {
                        if (isdongbo)
                        {
                            GridDB1.GetCell(i, colindex).Value = chk; break;
                            //CheckRow(gr2, colindex * 10, chk, root); 
                        }
                        else
                        {
                            GridDB1.GetCell(i, colindex).Value = true; break;
                            //CheckRow(gr2, colindex * 10, false, root);
                        }
                    }
                }
            }
        }

        private void dgvT_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (GridDB1.GetSelectedCells().Count == 0) { return; }
            GridCell gc = (GridCell)GridDB1.GetSelectedCells()[0];
            if (gc.ColumnIndex < 1 || gc.ColumnIndex > 6) { return; }
            GridRow gr = ((GridRow)GridDB1.PrimaryGrid.Rows[gc.RowIndex]);
            bool ischk = false;
            bool root = false;
            if (gr.Cells[gc.ColumnIndex].Value.ToString() != "")
            {
                ischk = gr.Cells[gc.ColumnIndex].Value.ToString() == "1" ? true : false;
                root = gr.Cells["clNotes"].Value.ToString() == "0" ? true : false;
                CheckRow(gr, gc.ColumnIndex, ischk, root);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckInput()) { return; }

            //update giá
            sql = string.Format("UPDATE tb0070 SET IsUpdateVoucherDate='{0}', IsLockUnitPrice='{1}' WHERE GroupID='{2}'", chkIsUpdateVoucherDate.Checked ? 1 : 0, chkIsLockUnitPrice.Checked ? 1 : 0, TDBCboGroupID.Text);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);

            //update phân quyên Division và GroupID

            string _divisionlist = "", _grouplist = "";

            if (lstDivisionShow.CheckedItems.Count > 0)
                foreach (string cl in lstDivisionShow.CheckedItems)
                    _divisionlist += "@" + cl.Substring(0,cl.IndexOf('.'));
            if (lstGroupShow.CheckedItems.Count > 0)
                foreach (string cl in lstGroupShow.CheckedItems)
                    _grouplist += "@" + cl.Substring(0, cl.IndexOf('.'));

            sql = string.Format("UPDATE tb0070 SET DivisionList='{0}', GroupList='{1}' WHERE GroupID='{2}'", _divisionlist, _grouplist, TDBCboGroupID.Text);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);
            
            // CHECK bảng phân quyền
            sql = string.Format("SELECT 1 FROM MK0001 WHERE GroupID='{0}'", TDBCboGroupID.Text);
            DataTable dtt = DATA.GetDataTable(sql, FRM.ConnectString);
            if(dtt.Rows.Count==0)
            {
                sql = "Insert MK0001 (TaskID , GroupID, IsNew, IsUpdate, IsDelete, IsView, IsPrint, IsExport, ";
			    sql += "CreateDate, CreateUserID, LastModifyUserID, LastModifyDate)";
		        sql += string.Format("Select ID, '{0}', 1,1,1,1,1,1,",TDBCboGroupID.Text);
			    sql += "getDate(), 'SABIADMIN',  'SABIADMIN', getdate() From MK0000";
                DATA.ExecuteNonQuery(sql, FRM.ConnectString);
            }

            // UPDATE phân quyền
            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                GridRow gr = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                sql = string.Format("Update MK0001 SET isNew='{0}', isView='{1}',", gr.Cells["clIsNew"].Value, gr.Cells["clIsView"].Value);
                sql += string.Format("isDelete='{0}', isPrint='{1}',", gr.Cells["clIsDelete"].Value, gr.Cells["clIsPrint"].Value);
                sql += string.Format("isUpdate='{0}', isExport='{1}' ", gr.Cells["clIsUpdate"].Value, gr.Cells["clIsExport"].Value);
                sql += string.Format(" Where GroupID='{0}' And TaskID='{1}'", TDBCboGroupID.Text, gr.Cells["clID"].Value.ToString());
                DATA.ExecuteNonQuery(sql, FRM.ConnectString);

            }

            // update thời gian thực cho user
            if(TDBCboGroupID.Text == FRM.ID_GroupList)
            {
                FRM.ID_DivisionList = _divisionlist;
                FRM.ID_GroupList = _grouplist;
            }

            SDLL.DLL02.Info("Cập nhật dữ liệu thành công!");
            loadDATA_Combo();
        }

        bool CheckInput()
        {
            if (TDBCboGroupID.SelectedItem == null) 
            { 
                return false; 
            }
            return true;
        }

        private void TDBCboGroupID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (TDBCboGroupID.SelectedItem != null)
            {
                _DivisionList = TDBCboGroupID.SelectedItem.ItemData[2];
                _GroupList = TDBCboGroupID.SelectedItem.ItemData[3];
                chkIsUpdateVoucherDate.Checked = TDBCboGroupID.SelectedItem.ItemData[4] == "1" ? true : false;
                chkIsLockUnitPrice.Checked = TDBCboGroupID.SelectedItem.ItemData[5] == "1" ? true : false;
                loadDATA_Grid1();
                btnSave.Enabled = true;
            }
            else
            {
                chkIsUpdateVoucherDate.Checked = false;
                chkIsLockUnitPrice.Checked = false;
                lstDivisionShow.Items.Clear();
                lstGroupShow.Items.Clear();
                GridDB1.PrimaryGrid.Rows.Clear();
                btnSave.Enabled = false;
            }
            chkDivision.CheckState = CheckState.Indeterminate;
            chkGroup.CheckState = CheckState.Indeterminate;
        }

        private void chkDivision_CheckedChanged(object sender, EventArgs e)
        {
            if (lstDivisionShow.Items.Count == 0) { return; }
            for (int i = 0; i < lstDivisionShow.Items.Count; i++)
                lstDivisionShow.SetItemChecked(i, chkDivision.Checked);
        }

        private void cbxGroup_CheckedChanged(object sender, EventArgs e)
        {
            if (lstGroupShow.Items.Count == 0) { return; }
            for (int i = 0; i < lstGroupShow.Items.Count; i++)
                lstGroupShow.SetItemChecked(i, chkGroup.Checked);
        }

        private void chkSelectAllLevel_CheckedChanged(object sender, EventArgs e)
        {
            if (GridDB1.PrimaryGrid.Rows.Count < 1) { return; }
            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                GridRow gr = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                for (int j = 1; j < 7; j++)
                    gr.Cells[j].Value = chkSelectAllLevel.Checked;
            }
        }

        private void chkOpenAllLevel_CheckedChanged(object sender, EventArgs e)
        {
            if (GridDB1.PrimaryGrid.Rows.Count < 1) { return; }
            for (int i = 0; i < GridDB1.PrimaryGrid.Rows.Count; i++)
            {
                GridRow gr = (GridRow)GridDB1.PrimaryGrid.Rows[i];
                if (gr.Cells["clNotes"].Value.ToString() == "0")
                {
                    gr.Cells["clOpen"].Value = chkOpenAllLevel.Checked;
                    SubRow(gr, chkOpenAllLevel.Checked);
                    HideRow(gr, chkOpenAllLevel.Checked);
                }
            }
        }

        private void GridDB2_SelectionChanged(object sender, GridEventArgs e)
        {
            GridRow gr = (GridRow)e.GridPanel.ActiveRow;
            if (gr == null) { return; }
            txtID.Text = gr["clID"].Value.ToString();
            txtFormID.Text = gr["clFormID"].Value.ToString();
            cbxModuleID.Text = gr["clModuleID"].Value.ToString();
            txtName.Text = gr["clName"].Value.ToString();

            //MessageBox.Show(gr["clParentID"].Value.ToString());
            if (gr["clParentID"].Value.ToString() != "0") { TDBParentID.SelectedValue = gr["clParentID"].Value.ToString(); }
            else { TDBParentID.Clear(); }
            chkDisabled.Checked = gr["clDisabled"].Value.ToString() == "1" ? true : false;
            txtID.Enabled = false;
            _Notes = gr["clNotes"].Value.ToString();
        }

        private void mRefresh_Click(object sender, EventArgs e)
        {
            loadDATA_Grid2();
        }

        private void mDelete_Click(object sender, EventArgs e)
        {
            if (!DLL02.Confirm("Bạn có chắc muốn xóa?")) { return; }

            int m;
            if(int.TryParse(txtID.Text,out m))
            {
                if (m % 1000 == 0)
                {
                    DLL02.Info("Bạn không thể xóa chức năng gốc của hệ thống!");
                    return;
                }
            }

            sql = string.Format("SELECT 1 FROM MK0000 WHERE ParentID='{0}'", txtID.Text);
            DataTable dt = FRM.GetDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                DLL02.Alert("ID này tồn tại chức năng con. \nVui lòng xóa các chức năng con, trước khi xóa chức năng này!");
                txtID.Focus();
                return;
            }

            sql = string.Format("DELETE MK0000 WHERE ID='{0}'", txtID.Text);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);

            sql = string.Format("DELETE MK0001 WHERE TaskID='{0}'", txtID.Text);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);

            DLL02.Info("Xóa dữ liệu thành công!");

            loadDATA_Grid2();
        }

        private void mAdd_Click(object sender, EventArgs e)
        {
            txtID.Text = "";
            txtFormID.Text = "";
            cbxModuleID.Text = "";
            txtName.Text = "";
            TDBParentID.Text = "";
            chkDisabled.Checked = false;
            txtID.Enabled = true;
            _Notes = "0";
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!CheckInput2()) { return; }
            if (txtID.Enabled) { SaveDATA(); }
            else { EditDATA(); }
                
        }
         
        bool CheckInput2()
        {
            TDBParentID_SelectedIndexChanged(null, null);
            if(txtID.Text.Trim()=="")
            {
                DLL02.Alert("ID không để trống!");
                txtID.Focus();
                return false;
            }
            else if (txtName.Text.Trim() == "")
            {
                DLL02.Alert("Tên không để trống!");
                txtName.Focus();
                return false;
            }
            
            return true;
        }

        void SaveDATA()
        {

            sql = string.Format("SELECT 1 FROM MK0000 WHERE ID='{0}'", txtID.Text);
            DataTable dt = FRM.GetDataTable(sql);
            if (dt.Rows.Count > 0)
            {
                DLL02.Alert("ID này đã tồn tại. Vui lòng chọn ID khác!");
                txtID.Focus();
                return;
            }

            sql = "INSERT MK0000(ID,Name,FormID,ModuleID,";
            sql += " ParentID, Notes, Disabled) VALUES(";
            sql += string.Format("'{0}',N'{1}','{2}','{3}',", txtID.Text, txtName.Text, txtFormID.Text, cbxModuleID.Text);
            sql += string.Format("'{0}','{1}','{2}')", TDBParentID.Text!=""?TDBParentID.Text:"0", _Notes, (chkDisabled.Checked ? 1 : 0));
            if(DATA.ExecuteNonQuery(sql, FRM.ConnectString))
            {
                sql = "Insert MK0001 (TaskID , GroupID, IsNew, IsUpdate, IsDelete, IsView, IsPrint, IsExport, ";
                sql += "CreateDate, CreateUserID, LastModifyUserID, LastModifyDate)";
                sql += string.Format("Select '{0}', GroupID , 1,1,1,1,1,1,", txtID.Text);
                sql += "getDate(), 'SABIADMIN',  'SABIADMIN', getdate() From tb0070 ";
                DATA.ExecuteNonQuery(sql, FRM.ConnectString);

                DLL02.Info("Lưu dữ liệu thành công!");
                loadDATA_Grid2();
            }
            else
            {
                DLL02.Info("Lưu dữ liệu thất bại!");
            }
                
        }

        void EditDATA()
        {
            sql = "UPDATE MK0000 SET ";
            sql += string.Format("Name = N'{0}',FormID = '{1}', ModuleID = '{2}',", txtName.Text, txtFormID.Text,cbxModuleID.Text);
            sql += string.Format(" ParentID = '{0}', Notes = '{1}', Disabled = '{2}' WHERE ID = '{3}'", TDBParentID.Text != "" ? TDBParentID.Text : "0", _Notes, (chkDisabled.Checked ? 1 : 0), txtID.Text);
            if (DATA.ExecuteNonQuery(sql, FRM.ConnectString))
            {
                //DLL02.Info("Cập nhật dữ liệu thành công!");
                loadDATA_Grid2();
            }
            else
            {
                DLL02.Info("Cập nhật dữ liệu thất bại!");
            }
        }

        private void txtName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { btnSave_Click(null, null); }
        }

        private void TDBParentID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(TDBParentID.SelectedItem==null){
                _Notes = "0";
                return;
            }
            int n;
            if(int.TryParse(TDBParentID.SelectedItem.ItemData[2],out n))
            {
                _Notes = (n+1).ToString();
            }
            else
            {
                _Notes = "0";
            }
        }

        private void btnUpdateLive_Click(object sender, EventArgs e)
        {
            (Application.OpenForms["frmHome"] as frmHOME).loadGUI_Form_Menu();
        }
    }
}
